import { getOssSignature } from '@/api/library_upload/upload'
import axios from 'axios'
import request from '@/utils/request'
import { Message } from 'element-ui'
import BMF from 'browser-md5-file'
import { v4 as uuidv4 } from 'uuid' // 使用 UUID 库
// 创建一个 CancelToken 实例
const CancelToken = axios.CancelToken

const uploadList = {
  namespaced: true,
  state: {
    uploadArr: []
  },
  getters: {
    uploadArr: state => state.uploadArr
  },
  mutations: {

    // 添加path
    addUploadItem(state, item) {
      state.uploadArr.push(item)
    },
    // 修改上传状态
    updateUploadStatus(state, { id, status }) {
      const itemIndex = state.uploadArr.findIndex(item => item.id === id)
      state.uploadArr[itemIndex].status = status
    },
    // 移除上传项
    removeUploadItem(state, id) {
      const itemIndex = state.uploadArr.findIndex(item => item.id === id)
      state.uploadArr.splice(itemIndex, 1)
    },

    // 改变上传进度
    changeProgress(state, { id, progress }) {
      const itemIndex = state.uploadArr.findIndex(item => item.id === id)
      state.uploadArr[itemIndex].progress = progress
    },
    // 取消上传
    cancelUpload(state, { id, c }) {
      const itemIndex = state.uploadArr.findIndex(item => item.id === id)
      state.uploadArr[itemIndex].cancel = c
    },
    // 获取上传文件bmf对象
    getBmfObj(state, { id, obj }) {
      const itemIndex = state.uploadArr.findIndex(item => item.id === id)
      state.uploadArr[itemIndex].bmfobj = obj
    },
    // 改变计算md5进度
    changeMD5Progress(state, { id, progress }) {
      const itemIndex = state.uploadArr.findIndex(item => item.id === id)
      state.uploadArr[itemIndex].md5progress = progress
    }
  },
  actions: {
    addArrItem({ commit }, file) {
      return new Promise((resolve) => {
        let id = uuidv4()
        let item = {
          id: id,
          fileName: file.name,
          fileSize: file.size,
          progress: 0,
          md5progress: 0,
          status: 4, // 0:计算资源中，1：上传中，2：上传成功，3：上传失败,4，排队中
          file: file,
          cancel: null,
          bmfobj: null
        }
        commit('addUploadItem', item)
        resolve(id)
      })
    },
    requestUpload({ commit }, params) {
      return new Promise((resolve, reject) => {
        let fileListCopy
        let filesReturn
        let dirPath
        const currentDate = new Date()
        const year = currentDate.getFullYear()
        const month = String(currentDate.getMonth() + 1).padStart(2, '0')
        const day = String(currentDate.getDate()).padStart(2, '0')

        const formattedDate = `${year}/${month}/${day}`
        fileListCopy = [params.file]
        filesReturn = []

        let sum = 0
        fileListCopy.forEach((file) => {
          const fileSize = file.size
          if (params.path) {
            dirPath = `${params.path}/${formattedDate}`

          }
          getOssSignature(dirPath).then((res) => {
            new Date().getTime()
            let formData = new FormData()
            formData.append(
              'key',
              `${dirPath}/${file.name}`
            )
            formData.append('OSSAccessKeyId', res.data.accessId)
            formData.append('policy', res.data.policy)
            formData.append('Signature', res.data.signature)
            formData.append('success_action_status', 200) // 成功后返回的操作码
            formData.append('file', file)
            commit('updateUploadStatus', { id: params.id, status: 1 })
            request({
              url: res.data.host,
              method: 'post',
              headers: {
                'Content-Type': 'multipart/form-data'
              },
              onUploadProgress(e) {
                commit('changeProgress', { id: params.id, progress: Math.round(e.loaded / e.total * 100) })
              },
              withCredentials: false,
              data: formData,
              // 使用取消令牌
              cancelToken: new CancelToken(function executor(c) {
                // 保存取消函数的引用
                commit('cancelUpload', { id: params.id, c })
              })
            })
              .then(() => {
                let obj = {
                  url: `${res.data.url.replace(
                    'https://hgcc-metaxun.oss-cn-hangzhou.aliyuncs.com',
                    'https://oss.metaxun.com'
                  )}/${file.name}`,
                  uploadStatus: 1,
                  fileSize: file.size,
                  fileName: file.name.slice(0, file.name.lastIndexOf('.')),
                  extendName: file.name.slice(file.name.lastIndexOf('.') + 1),
                  identifier: file.identifier
                }
                filesReturn.push(
                  obj
                )
                sum++
                if (sum == fileListCopy.length) {
                  // commit('updateUploadStatus', { id: params.id, status: 2 })
                  commit('removeUploadItem', params.id)
                  resolve(filesReturn)
                }
                // loading.setText(`正在上传,请稍等…(100%)`)
                // loading.close()
              })
              .catch((err) => {
                // loading.close();
                let obj = {
                  url: `${res.data.url.replace(
                    'https://hgcc-metaxun.oss-cn-hangzhou.aliyuncs.com',
                    'https://oss.metaxun.com'
                  )}/${file.name}`,
                  uploadStatus: 0,
                  fileSize: fileSize
                }
                filesReturn.push(
                  obj
                )
                reject(err)
              })
          })
        })
      })
    },
    // 计算MD5
    async uploadCheck({ commit }, params) {
      commit('updateUploadStatus', { id: params.id, status: 0 })
      let fileListCopy
      // 如果是数组
      if (params.file instanceof FileList) {
        fileListCopy = Array.from(params.file)
      }
      // 如果不是数组
      else {
        fileListCopy = [params.file]
      }
      let sum = 0
      const handleFilePromise = new Promise((resolve, reject) => {
        let num = 0
        for (const file of fileListCopy) {
          let selfSize = file.size / 1024 / 1024 // 转换为MB
          if (selfSize > 3072) {
            Message({
              message: `上传失败，单个文件大小不得超过3GB！`,
              type: 'warning'
            })
            commit('removeUploadItem', params.id)
            reject('单个文件大小不得超过3GB！')
            return
          }
          const fileSize = file.size
          sum += fileSize
          commit('getBmfObj', { id: params.id, obj: new BMF() })
          let uploadArr = this.state.uploadList.uploadArr
          const itemIndex = uploadArr.findIndex(item => item.id === params.id)
          uploadArr[itemIndex].bmfobj.md5(
            file,
            (err, md5) => {
              file.filePath = params.filePath
              file.parentId = params.parentId
              file.fileSize = file.size
              const lastDotIndex = file.name.lastIndexOf('.')
              const parts = [file.name.slice(0, lastDotIndex), file.name.slice(lastDotIndex + 1)]
              file.fileName = parts[0]
              file.extendName = parts[1]
              file.identifier = md5
              num++
              resolve(true)
            },
            (progress) => {
              const itemIndex1 = uploadArr.findIndex(item => item.id === params.id)
              if (uploadArr[itemIndex1]) {
                commit('changeMD5Progress', { id: params.id, progress: Math.round(progress * 100) })
                if (uploadArr[itemIndex1].bmfobj.aborted) {
                  console.log('222222')
                  commit('updateUploadStatus', { id: params.id, status: 3 })
                  reject('上传取消')
                }
              }
            }
          )

        }
      })
      const res = await handleFilePromise
      if (res) {
        if (params.map == 'group') {
          return request({
            url: '/netdisk/fileTransfer/preUploadGroupFile',
            method: 'post',
            data: {
              groupId: params.groupId,
              totalSize: sum,
              filePath: params.filePath,
              parentId: params.parentId,
              uploadFileList: fileListCopy
            }
          })
        } else {
          return request({
            url: '/netdisk/fileTransfer/preUploadFile',
            method: 'post',
            data: {
              totalSize: sum,
              filePath: params.filePath,
              parentId: params.parentId,
              uploadFileList: fileListCopy
            }
          })
        }
      }

    }
  }
}

export default uploadList
